<template>
  <div class="my-cu-plan-view">
    <div class="title">
      <div class="title-font">{{ title }}</div>
      <div class="back">
        <div @click="goBack"><i class="el-icon-back"></i>返回</div>
      </div>
    </div>
    <el-form :model="form" label-position="left" label-width="90px" ref="form" :rules="rules">
      <el-row :gutter="20" class="row">
        <el-col :span="6" style="height: calc(100vh - 160px);overflow-y: scroll">
          <p class="tip">基本信息</p>
          <div style="margin-left: 10px">
            <el-form-item label="计划名称" prop="name">
              <el-input v-model="form.name" autocomplete="off" maxlength="50" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="计划描述" prop="description" style="width: 100%">
              <el-input type="textarea" v-model="form.description" autocomplete="off"
                        :autosize="{ minRows: 2, maxRows: 4}" maxlength="200"></el-input>
            </el-form-item>
          </div>
          <p class="tip">配置信息</p>
          <div style="margin-left: 10px">
            <el-form-item label="性能模式" label-width="132px" prop="isHandless">
              <el-tooltip class="item" effect="dark" content="性能模式能减少内存和cpu的占用。启用后程序在后台运行，不调起浏览器" placement="top">
                <i class="el-icon-info"></i>
              </el-tooltip>
              <el-switch
                v-model="form.isHandless"
                :active-value=1
                :inactive-value=0
              ></el-switch>
            </el-form-item>
            <el-form-item label="出现异常截图" label-width="150px" prop="isShot">
              <el-switch
                v-model="form.isShot"
                :active-value=1
                :inactive-value=0
              ></el-switch>
            </el-form-item>
            <el-form-item label="运行结束关闭浏览器" label-width="150px" prop="isEndClose">
              <el-switch
                v-model="form.isEndClose"
                :active-value=1
                :inactive-value=0
              ></el-switch>
            </el-form-item>
            <el-form-item label="忽略异常并继续执行" label-width="150px" prop="isContinueRun">
              <el-switch
                v-model="form.isContinueRun"
                :active-value=1
                :inactive-value=0
              ></el-switch>
            </el-form-item>
          </div>
          <p class="tip">消息设置</p>
          <div style="margin-left: 10px">
            <el-form-item label="异常告警" label-width="" prop="isAlarm">
              <el-switch
                v-model="form.isAlarm"
                :active-value=1
                :inactive-value=0
              ></el-switch>
            </el-form-item>
            <el-form-item label="接收群组" prop="dingTalkId" v-if="form.isAlarm">
              <el-select v-model="form.dingTalkId" placeholder="请选择钉消息接收群组" style="width: 100%;">
                <el-option :label="item.dingTalkName" :value="item.dingTalkId"
                           v-for="item in dingTalkOptions"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="@所有人" label-width="" prop="atAll" v-if="form.isAlarm">
              <el-switch
                v-model="form.atAll"
                :active-value=1
                :inactive-value=0
              ></el-switch>
            </el-form-item>
            <el-form-item label="@联系人" prop="contactPerson" style="width: 100%" v-show="form.isAlarm && !form.atAll">
              <el-input type="textarea" v-model="form.contactPerson" autocomplete="off"
                        :autosize="{ minRows: 2, maxRows: 4}" maxlength="200"></el-input>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="18">
          <p class="tip">用例集合</p>
          <el-form-item prop="caseSet" label-width="0">
            <el-table
            class="my-table"
            :data="tableData"
            style="width: 100%"
            row-key="id"
            max-height="550px">
            <el-table-column label="" width="100px">
              <template>
                <i class="el-icon-rank" @mousedown="rowDrop" style="font-size: 24px"/>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号" width="80" :index="indexMethod"></el-table-column>
            <el-table-column prop="sceneName" label="所属场景" width="200"></el-table-column>
            <el-table-column prop="name" label="用例名称" width="200">
              <template slot-scope="scope">
                  <span @click="toCaseEdit(scope.row)" style="color: #0044f0;cursor:pointer;">{{
                      scope.row.name
                    }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="用例描述"></el-table-column>
            <el-table-column
              label="操作"
              width="100">
              <template slot-scope="scope">
                <el-button
                  @click.native.prevent="deleteStep(scope.$index)"
                  type="text"
                  size="small">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <report-dialog v-if="reportVisible" :dialogVisble="reportVisible" @closeDialog="closeDialog"
                   :respData="respData" :reportType="reportType"></report-dialog>
    <case-dialog v-if="caseVisible" :dialogVisble="caseVisible" @closeDialog="closeDialog"
                 @referenceData="referenceData"></case-dialog>
    <variable-dialog v-if="variableVisible" :dialogVisble="variableVisible"
                     @closeDialog="closeDialog"></variable-dialog>

    <div v-if="btnShow" class="bottom_btn">
      <div @click="caseVisible = true" class="btn_item fab-item-title fifthBtn">用例引用</div>
      <!--      <div @click="variableVisible = true" class="btn_item fab-item-title fifthBtn">场景变量</div>-->
      <div @click="debug" class="btn_item fab-item-title firstBtn">立即执行</div>
      <div @click="save" class="btn_item fab-item-title fourthBtn">保存计划</div>
    </div>
    <div class="optBtn">
      <el-button icon="el-icon-thumb" circle @click="btnShow = !btnShow" class="hand-btn"></el-button>
    </div>
  </div>
</template>

<script>
import VariableDialog from "../compoents/variableDialog";
import ReportDialog from "../compoents/reportDialog";
import Sortable from 'sortablejs'
import {deepClone, removeDuplicateObj, reMatch} from '@/utils/util'
import CaseDialog from "../compoents/caseDialog";
import {cron} from 'vue-cron';

export default {
  name: "cuView",
  components: {VariableDialog, ReportDialog, CaseDialog, cron},
  data() {
    let checkCaseSet = (rule, value, callback) => {
      if (this.tableData.length === 0) {
        callback(new Error('用例集合不能为空'));
      } else {
        callback();
      }
    };
    return {
      cronPopover: false,
      btnShow: true,
      reportType: 'plan',
      photo: "",
      title: "",
      editData: {},
      editStepData: {},
      form: {
        name: "",
        description: "",
        caseIds: [],
        isHandless: 0,
        isEndClose: 1,
        isContinueRun: 0,
        isShot: 0,
        isAlarm: 0,
        atAll: 1,
        dingTalkId: "",
        contactPerson: "",
        projectId: "",
        createUser: ""
      },
      tableData: [],
      rules: {
        name: [{required: true, message: '计划名称不能为空', trigger: 'blur'}],
        caseSet: [{required: true, validator: checkCaseSet, message: '用例集合不能为空', trigger: 'change'}]
      },
      reportVisible: false,
      caseVisible: false,
      variableVisible: false,
      respData: [],
      list: [],
      caseIds: [],
      caseName: "",
      dingTalkOptions: []
    }
  },
  created() {
    this.title = this.$route.query.title
    let planId = sessionStorage.getItem("planId")
    if (planId) {
      this.getPlanInfo(planId)
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    }
  },
  mounted() {
    this.rowDrop();
    this.getDingTalkConfigList();
  },
  methods: {
    getDingTalkConfigList() {
      this.api({
        url: "/getDingTalkConfigList",
        method: "post",
        data: {
          pageRow: 100,
          pageNum: 1
        }
      }).then(resp => {
        this.dingTalkOptions = resp.list;
      });
    },
    getPlanInfo(planId) {
      this.api({url: `/getPlanInfoById/${planId}`, method: "get"}).then((resp) => {
        let data = resp
        data.caseIds = JSON.parse(data.caseIds)
        this.caseIds = data.caseIds
        this.form = {...data}
        this.getCaseList({caseIds: data.caseIds})
      })
    },
    // 行拖拽
    rowDrop() {
      // 此时找到的元素是要拖拽元素的父容器
      const tbody = document.querySelector(".el-table__body-wrapper tbody");
      const _this = this;
      Sortable.create(tbody, {
        //  指定父元素下可被拖拽的子元素
        draggable: ".el-table__row",
        onEnd({newIndex, oldIndex}) {
          const currRow = _this.tableData.splice(oldIndex, 1)[0];
          _this.tableData.splice(newIndex, 0, currRow);
          _this.sortCaseWeb();
        }
      });
    },
    // 重新排序
    sortCaseWeb() {
      for (let i = 0; i < this.tableData.length; i++) {
        this.tableData[i].index = i + 1;
      }
    },
    indexMethod(index) {
      return index + 1;
    },
    toCaseEdit(row) {
      sessionStorage.setItem("caseId", row.id)
      this.$router.push({path: 'cuView', query: {title: "编辑用例"}}) // 只能用 name
    },
    getCaseList(body) {
      body["projectId"] = this.projectId
      if (body.caseIds.length > 0) {
        this.api({url: "/getCaseListByIds", method: "post", data: body}).then(resp => {
          this.tableData = resp.caseList
        })
      }
    },
    restList() {
      this.query.pageNum = 1;
      this.closeDialog()
    },
    closeDialog() {
      this.reportVisible = false;
      this.caseVisible = false;
      this.variableVisible = false;
    },
    referenceData(data) {
      try {
        this.tableData.forEach(item => {
          if (item.id == data.id) {
            this.$message.warning({message: "已存在相同用例"});
            throw new Error('已存在相同用例！');
          }
        })
        this.$message.success("引用：" + `${data.name}` + " 成功")
        this.tableData.push(data)
        let caseIds = this.tableData.map(item => item.id)
        this.caseIds = caseIds
        this.getCaseList({caseIds: caseIds})
      } catch (e) {
        console.log(e)
      }
    },
    goBack() {
      this.$router.push({"path": "/ui/plan"})
    },
    deleteStep(index) {
      if (index !== -1) {
        this.tableData.splice(index, 1)
        let caseIds = []
        if (this.tableData.length === 0) {
          caseIds = []
        } else {
          this.tableData.forEach(item => {
            caseIds.push(item.id)
          })
        }
        this.caseIds = caseIds
        this.getCaseList({caseIds: caseIds})
      }
    },
    save() {
      this.$refs.form.validate(valid => {
        if (valid) {
          let newForm = JSON.parse(JSON.stringify(this.form))
          newForm.projectId = window.sessionStorage.getItem("projectId");
          newForm.caseIds = JSON.stringify(this.tableData.map(item => item.id))
          if (this.title === "新建计划") {
            newForm.createUser = this.$store.state.user.userId;
            this.api({url: "/addPlan", method: "post", data: newForm}).then(resp => {
              this.goBack();
              this.$message({message: resp, type: 'success'});
            })
          } else {
            newForm.updateUser = this.$store.state.user.userId;
            this.api({url: "/updatePlan", method: "put", data: newForm}).then(resp => {
              this.$message({message: resp, type: 'success'});
            })
          }
        }
      })
    },
    debug() {
      this.$refs.form.validate(valid => {
        if (valid) {
          let newForm = JSON.parse(JSON.stringify(this.form))
          newForm.projectId = window.sessionStorage.getItem("projectId");
          newForm.createUser = this.$store.state.user.userId;
          newForm.caseIds = this.caseIds;
          const loading = this.$loading({
            lock: true, // lock的修改符--默认是false
            text: 'Loading', // 显示在加载图标下方的加载文案
            spinner: 'el-icon-loading', // 自定义加载图标类名
            background: 'rgba(0, 0, 0, 0.7)', // 遮罩层颜色
            target: document.querySelector('#table')//loading覆盖的dom元素节点
          })
          this.api({url: "/runPlan", method: "post", data: newForm}).then(resp => {
            loading.close()
            this.respData = resp;
            this.reportType = 'plan';
            this.reportVisible = true;
          })
        }
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.my-cu-plan-view {
  margin: 20px;
  background-color: white;
  height: calc(100vh - 110px);

  .el-date-editor--datetime {
    width: 100%;
  }

  .tree-column {
    text-align: left;
  }

  .zip-icon {
    width: 14px;
    height: 14px;
  }

  .my-table {
    overflow-y: scroll !important;
  }

  .tip {
    padding: 0 5px;
    font-size: 16px;
    border-radius: 0;
    border-left: 4px solid #0044f0;
    font-weight: 700;
  }

  .title {
    height: 50px;
    padding: 0 20px;
    border-bottom: 1px solid #ddd;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex: 0 0 auto;
  }

  .title-font {
    font-size: 20px;
    color: #333;
    line-height: 1;
    font-weight: 700;
  }

  .back {
    position: relative;
    font-size: 14px;
    color: #0044f0;
    line-height: 1;
    cursor: pointer;
    margin-right: 10px;
  }

  .row {
    padding: 0 20px;
  }

  .el-icon-back {
    margin-right: 5px;
    font-size: 16px;
  }

  .bottom_btn {
    position: fixed;
    bottom: 35px;
    right: 80px;

    .firstBtn {
      color: rgb(245, 108, 108);
      background: rgb(252, 241, 241);
    }

    .secondBtn {
      color: rgb(0, 128, 128);
      background: rgb(235, 242, 242);
    }

    .thirdBtn {
      color: rgb(2, 167, 240);
      background: rgb(244, 244, 245);
    }

    .fourthBtn {
      color: rgb(103, 194, 58);
      background: rgb(242, 249, 238);
    }

    .fifthBtn {
      color: rgb(230, 162, 60);
      background: rgb(252, 246, 238);
    }

    .fab-item-title {
      cursor: pointer;
      box-shadow: 0 1px 0.5px #ccc;
      padding: 5px 5px;
      font-size: 14px;
      min-width: 5em;
      white-space: nowrap;
      border-radius: 2px;
      text-align: center;
      display: inline-block;
    }
  }

  .optBtn {
    position: fixed;
    right: 40px;
    color: #FFF;
    bottom: 30px;

    .hand-btn {
      background-color: #0044f0 !important;
      border-color: #0044f0 !important;
      color: white;
    }
  }
}


</style>
